import React, {useRef, useState} from 'react';
import {Image, message, Upload} from 'antd';
import type { ProFormInstance} from '@ant-design/pro-components';
import {
  ProFormSelect,
  ProFormText,
  ProForm,
  ProFormTreeSelect, DrawerForm, ProFormSwitch
} from '@ant-design/pro-form';
import type { UserItem } from '../data';
import {queryDeptTree, queryRoleItem, queryUserItem} from "@/pages/User/service";
import type {RequestOptionsType} from "@ant-design/pro-utils";
import ImgCrop from "antd-img-crop";
import type {RcFile, UploadFile} from "antd/es/upload/interface";
import type {UploadProps} from "antd/es";

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<UserItem>;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<UserItem>;
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  /** ModalForm中头像上传的预览 */
  const [fileList, setFileList] = useState<UploadFile[]>([
    // {
    //   uid: '-1',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    // },
  ]);

  // ModalForm更新入口
  const update_formRef = useRef<ProFormInstance>();
  const onChange: UploadProps['onChange'] = ({file,fileList: newFileList }) => {
    // 上传文件
    setFileList(newFileList);
    // 获取返回
    const res = file.response;
    if(res){
      // 有返回结果时，进行判断
      if(res.status === "done"){
        // 保存成功，给Form回填数值
        /**
         * 由于ProForm的文件上传字段，并不包含在FORM表单中。无法在上传完毕后自动关联;
         * 1，在FORM中增加一个隐藏字段：
         *     <ProFormText name="avatar" hidden={true}/>
         * 2， 在ModalForm中增加 formRef={formRef} 属性
         * 3， 在处理文件上传的onchange函数前增加formRef入口
         *        // ModalForm更新入口
         *        const formRef = useRef<ProFormInstance>();
         * 4，上传完成时，给隐藏字段赋值：
         *         formRef?.current?.setFieldsValue({
         *           avatar: res.url
         *         })
         * 通过以上算步，可以将通过文件上传接口上传的文件，关联到当前FORM表单中。
         */

        update_formRef?.current?.setFieldsValue({
          avatar: res.url    // 可以绑定后台返回的name或者url，或者fid，根据需求，取对应的数据
        })
        // message.success(res.message)
      }else {
        // 后台返回错误，需要告知前台
        message.error(res.message)
      }
    }
  };

  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as RcFile);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    // const image = new Image();
    // image.src = src;
    // const imgWindow = window.open(src);
    // imgWindow?.document.write(image.outerHTML);
  };

  return (
    <DrawerForm
      title="修改用户"
      open={props.updateModalVisible}
      // width={640}
      initialValues={{
        username: props.values.username,
        nickname: props.values.nickname,
        gender: props.values.gender,
        email: props.values.email,
        mobile: props.values.mobile,
        avatar: props.values.avatar,
        isActive: props.values.isActive,
        isSuperuser: props.values.isSuperuser
      }}

      formRef={update_formRef}
      // Drawer抽屉需要关联上层UpdateForm的点击管理函数
      onFinish={props.onSubmit}
      drawerProps={{
        destroyOnClose: true,
        // 抽屉层关闭函数， 需要关联上层的onCancel函数
        onClose: function (){
          props.onCancel()
        },
      }}
    >
      <ProForm.Group>
        <ProFormText
          rules={[
            {
              required: true,
              message: '用户名为必填项',
            },
          ]}
          width="sm"
          name="username"
          label={"用户名"}
          disabled={true}
        />
        <ProFormText
          width="sm"
          name="nickname"
          label={"姓名"}
          rules={[
            {
              required: true,
              message: '姓名为必填项',
            },
          ]}
        />
        <ProFormSelect
          name="gender"
          label={"性别"}
          width="sm"
          options={[
            {value: 0, label: "女"},
            {value: 1, label: "男"},
            {value: 2, label: "未知"},
          ]}
          rules={[{required: true, message: '性别是必选项',},]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          width="md"
          name="email"
          label={"邮箱"}
          rules={[
            {pattern: /^[a-zA-Z\d_.-]+@[a-zA-Z\d-]+(\.[a-zA-Z\d-]+)*\.[a-zA-Z\d]{2,6}$/, message:'邮箱格式不正确！'},
            {max: 50, message:'邮箱不得超过50字符！'}
          ]}/>
        <ProFormText
          width="md"
          name="mobile"
          label={"手机号码"}
          rules={[
            { pattern: /^((13\d)|(14[5,7])|(15[^4,\\D])|(17[0,1,3,6-8])|(18\d)|(19[8,9])|(166))\d{8}$/,
              message:'手机号码格式不正确！'}
          ]}/>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText name="password" label="密码" placeholder={"如无需重置密码，请勿输入！"} width="md" />
        <ProFormText name="avatar" width="md" hidden={true}/>
        <ProFormSwitch checkedChildren="是" unCheckedChildren="否" width={"md"} name="isSuperuser" label="超级管理员" />
        <ProFormSwitch checkedChildren="有效" unCheckedChildren="禁用" width={"md"} name="isActive" label="账号激活" />
      </ProForm.Group>
      <ProForm.Group>
        <ImgCrop>
          <Upload
            /**
             *   {fileList.length < 1 && '上传头像'}  设置上传数量限制
             *   action需要添加post上传文件的后端连接
             */
            name="file"
            accept="image/*"
            listType="picture-card"
            action="/api/upload?path=avatar"   // 上传接口，不支持添加到form的形式post上传
            fileList={fileList}
            onChange={onChange}
            onPreview={onPreview}
          >
            {fileList.length < 1 && '修改头像'}
          </Upload>
        </ImgCrop>
      </ProForm.Group>
      <ProForm.Group>
        <Image width={100} src={props.values.avatar} />
      </ProForm.Group>
    </DrawerForm>
  );
};

export default UpdateForm;
